package com.example.zlpermissionservice.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.zlpermissionservice.entity.UserRole;
import com.example.zlpermissionservice.mapper.UserRoleMapper;
import com.example.zlpermissionservice.service.IUserRoleService;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;

/**
 * @Author zhenliu（孙凌岳）
 * @Description TODO
 * @Date 2025/6/17 16:20
 * @Version 1.0
 */

@Service
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRole> implements IUserRoleService {
    @Resource
    private UserRoleMapper userRoleMapper;

    /**
     * 批量新增用户角色关联信息
     * @param userRoleList
     * @return
     */
    @Override
    @GlobalTransactional
    public int batchInsert(List<UserRole> userRoleList) {
        boolean result = this.saveBatch(userRoleList);
        return result ? userRoleList.size() : 0;
    }

    /**
     * 根据id删除 用户角色关联信息
     * @param userId
     * @return
     */
    @Override
    @GlobalTransactional
    public Boolean deleteUserRoleByUserId(Long userId) {
        return lambdaUpdate()
                .eq(UserRole::getUserId, userId)
                .remove();
    }

    /**
     * 批量删除
     * @param userIds
     * @return
     */
    @Override
    public Boolean deleteByUserIds(List<Long> userIds){
        return lambdaUpdate()
                .in(UserRole::getUserId, userIds)
                .remove();
    }

    /**
     * 根据角色id获取已经绑定此角色的用户id列表
     * @param roleId
     * @return
     */
    @Override
    public List<Long> getUserIdsByRoleId(Long roleId) {
        if (ObjectUtil.isNull(roleId)) {
            return Collections.emptyList();
        }

        return userRoleMapper.findUserIdsByRoleId(roleId);
    }
}
